package com.example.exchangeapp.zjs;

import static android.content.ContentValues.TAG;

import static com.example.exchangeapp.yy.constant.AppId.AppId;
import static com.example.exchangeapp.yy.constant.AppSecret.appSecret;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.example.exchangeapp.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchResultActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private final Gson gson = new Gson();
    private Handler uiHandler = new Handler(Looper.getMainLooper());

    //模糊查询请求获取到的商品列表
    private String searchProductName;
    private List<Product> searchProductList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        // 获取 RecyclerView 实例
        recyclerView = findViewById(R.id.recyclerViewSearchResult);

        // 获取用户输入的商品名称
        searchProductName = getIntent().getStringExtra("searchProductName");
        // 执行商品查询操作
        performProductSearchTotal(searchProductName);

        // 使用瀑布流布局
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);;

    }

    //搜索框模糊搜索获取商品总数
    private void performProductSearchTotal(String productName) {
        new Thread(() -> {

            //用户id
            int id = 57;

            GetUserStatus getUserStatus=new GetUserStatus(this);
            Cursor cursor=getUserStatus.getDataFromDatabase();
            while (cursor.moveToNext()){
                int index0=cursor.getColumnIndex("ID");
                id=cursor.getInt(index0);
            }
            String userId = (String.valueOf(id));
            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/goods/all?keyword="+productName+"&userId="+userId;

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackSearchProductTotal);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callbackSearchProductTotal = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            ProductResponse dataResponseBody = gson.fromJson(body, ProductResponse.class);
            Log.d("商品信息为", "商品信息为"+dataResponseBody.toString());

            // 模糊查询获取的商品总数和列表
            Integer productTotal = dataResponseBody.getData().getTotal();
            performProductSearch(searchProductName,productTotal);
        }
    };


    //搜索框模糊搜索商品
    private void performProductSearch(String productName,Integer productTotal) {
        new Thread(() -> {

            //用户id
            int id = 57;

            GetUserStatus getUserStatus=new GetUserStatus(this);
            Cursor cursor=getUserStatus.getDataFromDatabase();
            while (cursor.moveToNext()){
                int index0=cursor.getColumnIndex("ID");
                id=cursor.getInt(index0);
            }
            String userId = (String.valueOf(id));
            // 请求的url路径
            String url = "http://47.107.52.7:88/member/tran/goods/all?keyword="+productName+"&size="+productTotal+"&userId="+userId;

            //我的f9ed7014c8cb45169ab4cc0728775790和26073a2f31b8baca64eca93c3c2c5a3dd2313
            //yy的ea0f4556cf414613a551ca2c25840189和139172f805f8d3e654ffb891d963d96f64f62
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId)
                    .add("appSecret", appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callbackSearchProduct);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callbackSearchProduct = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "连接服务器失败!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("json串为", body);
            // 解析json串到自己封装的状态
            ProductResponse dataResponseBody = gson.fromJson(body, ProductResponse.class);
            Log.d("商品信息为", "商品信息为"+dataResponseBody.toString());

            // 模糊查询获取的商品列表
            searchProductList = dataResponseBody.getData().getRecords();

            // 使用Handler在主线程中更新UI
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 在这里创建适配器并设置到RecyclerView
                    ProductAdapter adapter = new ProductAdapter(searchProductList);
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    };
}
